import React, { useState, useEffect, useContext } from "react";
import { Link, useLocation } from "react-router-dom";
import { AppState } from "../App";
import "../css/songwarm.css";
import "../css/background.css";
import "../css/loader.css";
import ProgressBar from "./ProgressBar";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faThumbsUp, faDonate } from "@fortawesome/free-solid-svg-icons";
import { Flex, Progress } from "antd";

const SongWarm = () => {
  const App = useContext(AppState);
  const [Data, setData] = useState([]);
  const [num, setNum] = useState(0);
  const [Balance, setBalance] = useState("");
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const title = searchParams.get("tittle");
  const [loading, setLoading] = useState(true);
  const [progress, setProgress] = useState(0);
  const itemsPerPage = 1; //每页显示的数量
  const [currentPage, setCurrentPage] = useState(1);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = Data.slice(indexOfFirstItem, indexOfLastItem);
  const pageNumbers = [];
  const [Pcount, setPcount] = useState("");
  const [isOngoing, setIsOngoing] = useState(true);
  const [showCompleted, setShowCompleted] = useState(false);
  for (let i = 1; i <= Math.ceil(Data.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }

  const handleClick = (pageNumber) => {
    setCurrentPage(pageNumber);
  };
  const Vote = async (nums) => {
    try {
      const tx = await App.Foundationcontract.voteRequest(nums);
      await tx.wait();
      alert("投票成功");
      setNum(num + 1);
    } catch (error) {
      if (error.message === "YOu must be contributor") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };

  const Donate = async (id) => {
    try {
      const tx = await App.Foundationcontract.executeRequest(id);
      await tx.wait();
      alert("捐赠成功！");
      setNum(num + 1);
    } catch (error) {
      if (error.message == "execution reverted: You already Voted") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };

  useEffect(() => {
    const getBal = async () => {
      try {
        const Balance = await App.Foundationcontract.getBalance();
        const totalContributors =
          await App.Foundationcontract.contributorsNumber();
        setBalance(Balance);
        setPcount(totalContributors);
      } catch (error) {
        console.log(error);
      }
    };
    getBal();
  }, [App.Foundationcontract]);

  const calculateRemainingTime = (endTime, completed) => {
    if (completed) {
      return "已结束";
    }
    const now = new Date().getTime();
    const end = endTime * 1000;
    const distance = end - now;
    if (distance < 0) {
      return "已结束";
    }
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor(
      (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
  };

  useEffect(() => {
    if (App.Foundationcontract) {
      const getProposals = async () => {
        try {
          const Count = await App.Foundationcontract.requestsNumber();
          let proposals = [];
          let ongoingProposals = [];
          let completedProposals = [];
          for (let i = 0; i < Count; i++) {
            const Proposal = await App.Foundationcontract.requestions(i);
            const updatedProposal = {
              ...Proposal,
              remainingTime: calculateRemainingTime(
                Proposal.endTime,
                Proposal.completed
              ),
            };

            if (title && updatedProposal.tittle !== title) {
              continue;
            }

            if (
              (isOngoing && updatedProposal.remainingTime !== "已结束") ||
              (!isOngoing && updatedProposal.remainingTime === "已结束")
            ) {
              proposals.push(updatedProposal);
              if (Proposal.completed) {
                completedProposals.push(updatedProposal);
              } else {
                ongoingProposals.push(updatedProposal);
              }
            }
            const progress = ((i + 1) / Count) * 100;
            setProgress(progress);
          }
          const proposalsToShow = showCompleted
            ? completedProposals
            : ongoingProposals;
          const shuffledProposals = proposalsToShow.sort(
            () => Math.random() - 0.5
          );
          setData(shuffledProposals);
          setLoading(false);
        } catch (error) {
          console.log(error);
        }
      };
      getProposals();
    }
  }, [App.Foundationcontract, num, title, isOngoing, showCompleted]);

  const calculatePercentage = (votersNumber) => {
    const percentage = (votersNumber / Pcount) * 100;
    return percentage > 50 ? 100 : percentage;
  };

  useEffect(() => {
    const interval = setInterval(() => {
      setData((prevData) =>
        prevData.map((item) => {
          return {
            ...item,
            remainingTime: calculateRemainingTime(item.endTime, item.completed),
          };
        })
      );
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div className="SongwarmDivFFF">
      {loading && <ProgressBar progress={progress} />}
      <div className="Songwarmcontainer">
        <div className="Songwarmblance">
          <h1>基金会余额 - {Balance.toString()} 爱心币</h1>
          <h1>现总捐款人数 - {Pcount.toString()} 人</h1>
        </div>
        <div className="songwarmBtnDiv">
          <button
            className={`toggle-button ${isOngoing ? "active" : ""}`}
            onClick={() => {
              setIsOngoing(true);
              setShowCompleted(false);
            }}
          >
            正在进行
          </button>
          <button
            className={`toggle-button ${
              !isOngoing && !showCompleted ? "active" : ""
            }`}
            onClick={() => {
              setIsOngoing(false);
              setShowCompleted(false);
            }}
          >
            已截止
          </button>

          <button
            className={`toggle-button ${showCompleted ? "active" : ""}`}
            onClick={() => {
              setIsOngoing(false);
              setShowCompleted(true);
            }}
          >
            已拨款
          </button>
        </div>

        <div className="new-layout">
          {currentItems.length !== 0 ? (
            currentItems.map((e, id) => {
              const photos = e.photo.split(",");
              const percentage = calculatePercentage(
                Number(e.votersNumber.toString())
              );
              // console.log(e.remainingTime)
              return (
                <div className="item-container" key={id}>
                  <div className="left-content">
                    <div className="left_img">
                      <img
                        src={
                          photos.length > 0
                            ? `https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${photos[0]}`
                            : "/images/love.jpg"
                        }
                        style={{ width: 99.9, height: 79.9 }}
                      />
                    </div>
                    <div className="left_right">
                      <div className="description">
                        <p>{e.description}</p>
                      </div>

                      <div className="category">
                        <p>
                          {e.tittle}--{Number(e.targetMoney.toString())}{" "}
                          爱心币(所需金额)
                        </p>
                        <p>剩余时间--{e.remainingTime}</p>
                      </div>

                      <div className="button-container">
                        <button
                          onClick={() => Vote(Number(e.uniqueid.toString()))}
                          className="voted_button"
                        >
                          <FontAwesomeIcon icon={faThumbsUp} />
                          {e.votersNumber.toString()}
                          <span className="tooltiptext">投票</span>
                        </button>
                        <button
                          onClick={() => Donate(Number(e.uniqueid.toString()))}
                          className="voted_button"
                        >
                          <FontAwesomeIcon icon={faDonate} />
                          <span className="tooltiptext">拨款</span>
                        </button>
                        <Flex gap="small" wrap>
                          <Progress
                            type="dashboard"
                            percent={percentage}
                            width={53} // 设置进度条的宽度
                            strokeWidth={8} // 设置进度条的粗细
                          />
                        </Flex>
                      </div>
                    </div>
                  </div>
                  <div className="right-content">
                    {photos.slice(0, 3).map((photo, idx) => (
                      <Link
                        key={idx}
                        to={`/header/songwarm/${e.uniqueid}`}
                        className="image-link"
                      >
                        <img
                          src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${photo}`}
                          alt={`Proposal Photo ${idx + 1}`}
                        />
                        {idx === 2 && photos.length > 3 && (
                          <div className="overlay">
                            <h2 className="overlay-text">
                              +{photos.length - 3} 张
                            </h2>
                            <p className="overlay-text">查看所有图片</p>
                          </div>
                        )}
                      </Link>
                    ))}
                  </div>
                </div>
              );
            })
          ) : (
            <div className="flex items-center justify-center nonDIv">
              <div className="title-font text-xl font-medium text-gray-900 mb-3 text-black">
                没有找到相关内容。
              </div>
            </div>
          )}
        </div>
        {currentItems.length !== 0 && (
          <div className="swpagination-container">
            <button
              className={`swpagination-button ${
                currentPage === 1 ? "disabled" : ""
              }`}
              onClick={() => handleClick(currentPage - 1)}
              disabled={currentPage === 1}
            >
              上一页
            </button>
            {pageNumbers.map((number) => (
              <button
                key={number}
                className={`swpagination-button ${
                  currentPage === number ? "active" : ""
                }`}
                onClick={() => handleClick(number)}
              >
                {number}
              </button>
            ))}
            <button
              className={`swpagination-button ${
                currentPage === pageNumbers.length ? "disabled" : ""
              }`}
              onClick={() => handleClick(currentPage + 1)}
              disabled={currentPage === pageNumbers.length}
            >
              下一页
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default SongWarm;
